package com.md.client;

import com.md.api.OpenLogsApi;
import com.md.client.helper.DefaultOpenLogsController;
import com.md.model.system.CommonResult;
import com.md.request.OperationLogsRequest;
import com.md.response.LogsResponse;
import com.md.util.ObjectUtil;
import com.md.util.SpringContextUtil;
import com.md.util.StringUtil;
import com.md.value.enums.ErrorEnum;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import static com.md.value.constants.CodeConstants.SUCCESS_CODE;

/**
 * @author 刘骄阳
 * 2024-10-11 11:22
 */
@UtilityClass
@Slf4j
public class OpenLogsClient {
  private OpenLogsApi openLogsApi;

  private static OpenLogsApi getOpenLogsApi() {
    if (ObjectUtil.isEmpty(openLogsApi)) {
      openLogsApi = SpringContextUtil.getBean(DefaultOpenLogsController.class);
    }
    return openLogsApi;
  }

  private static CommonResult<LogsResponse> create(final OperationLogsRequest request) {
    OpenLogsApi tempOpenLogsApi = getOpenLogsApi();
    if (ObjectUtil.isEmpty(tempOpenLogsApi)) {
      return CommonResult.error(ErrorEnum.UN_EXISTENT);
    }
    return tempOpenLogsApi.create(request);
  }

  private static CommonResult<LogsResponse> update(final OperationLogsRequest request) {
    OpenLogsApi tempOpenLogsApi = getOpenLogsApi();
    if (ObjectUtil.isEmpty(tempOpenLogsApi)) {
      return CommonResult.error(ErrorEnum.UN_EXISTENT);
    }
    return tempOpenLogsApi.update(request);
  }

  public static void recordOperatorLog(final OperationLogsRequest request) {
    try {
      CommonResult<LogsResponse> result = create(request);
      if (ObjectUtil.equals(result.getCode(), SUCCESS_CODE)) {
        log.info("日志记录成功: {}", StringUtil.objectToJson(request));
        return;
      }
      log.error("日志记录失败({}): {}", result.getCode(), result.getMessage());
    } catch (Exception e) {
      log.error("日志记录失败: {}", e.getMessage(), e);
    }
  }

  public static void updateOperatorLog(final OperationLogsRequest request) {
    try {
      CommonResult<LogsResponse> result = update(request);
      if (ObjectUtil.equals(result.getCode(), SUCCESS_CODE)) {
        log.info("日志记录成功: {}", StringUtil.objectToJson(request));
        return;
      }
      log.error("日志记录失败({}): {}", result.getCode(), result.getMessage());
    } catch (Exception e) {
      log.error("日志记录失败: {}", e.getMessage(), e);
    }
  }
}
